// Replace require with import
import axios from 'axios';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

// Get the current file path
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Replace with your own Gaode Map API Key
const apiKey = '075e35ac93711165ae846120546c4e9c';

// Build the request URL
const url = `https://restapi.amap.com/v3/config/district?keywords=中国&subdistrict=3&key=${apiKey}`;

// Send the request
axios.get(url)
  .then(response => {
    const districts = response.data.districts[0].districts;
    const citiesData = {};

    // 处理省级数据
    districts.forEach(province => {
      const provinceName = province.name;
      const provinceCities = {};

      // 处理市级数据
      province.districts.forEach(city => {
        const cityName = city.name;
        const cityAreas = [];

        // 处理区级数据
        city.districts.forEach(district => {
          cityAreas.push(district.name);
        });

        provinceCities[cityName] = cityAreas;
      });

      citiesData[provinceName] = provinceCities;
    });

    // 写入文件
    const filePath = path.join(__dirname, 'f:/S4/TS/karen.admin-2/Karen.Admin/src/components/CustomerVip/cities.json');
    fs.writeFileSync(filePath, JSON.stringify(citiesData, null, 2));
    console.log('省市区数据已成功写入 cities.json 文件。');
  })
  .catch(error => {
    console.error('请求出错:', error);
  });